package com.myslef.teaching_platfrom.controller;


import com.myslef.teaching_platfrom.common.R;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.core.io.Resource;
import org.springframework.core.io.ResourceLoader;
import org.springframework.core.io.UrlResource;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.ArrayList;
import java.util.List;

@RestController
@RequestMapping
@CrossOrigin(origins = "http://localhost:8080")
public class UploadController {

    @Autowired
    private ResourceLoader resourceLoader;


    @Value("${upload.dir}") // 读取配置文件中的上传文件保存目录
    private String uploadDir;


    @GetMapping("/uploads/{filename:.+}")
    public ResponseEntity<byte[]> getImage(@PathVariable String filename) throws IOException {
        File file = new File(uploadDir+filename);
        InputStream inputStream = new FileInputStream(file);
        byte[] bytes = new byte[inputStream.available()];
        inputStream.read(bytes);
        inputStream.close();
        // 设置HTTP响应头
        HttpHeaders headers = new HttpHeaders();
        headers.setContentType(MediaType.IMAGE_JPEG);
        // 返回图片内容给前端
        return new ResponseEntity<>(bytes, headers, HttpStatus.OK);
    }

    @GetMapping("/download/{fileName:.+}")
    public ResponseEntity<Resource> downloadDocxFile(@PathVariable String fileName) throws IOException {

        Path filePath = Paths.get(uploadDir+fileName);
        System.out.println(uploadDir+fileName);
        Resource resource = new UrlResource(filePath.toUri());

        HttpHeaders headers = new HttpHeaders();
        headers.add(HttpHeaders.CONTENT_DISPOSITION, "attachment; filename=\"" + resource.getFilename() + "\"");

        return ResponseEntity.ok()
                .headers(headers)
                .contentType(MediaType.parseMediaType("application/vnd.openxmlformats-officedocument.wordprocessingml.document"))
                .body(resource);
    }





    @PostMapping("/uploadTask")
    public R createComment(@RequestParam(required = false,value = "file") MultipartFile[] files) throws IOException {

        // 创建上传目录
        Path uploadPath = Paths.get(uploadDir+"/task/"+System.currentTimeMillis());
        if(files != null)
        System.out.println("uploadTask:"+uploadPath.toString());
        List<String> list = new ArrayList<>();
        if(files != null)
            for (int i = 0; i < files.length; i++) {
                String originalFileName = files[i].getOriginalFilename();
                String fileExtension = originalFileName.substring(originalFileName.lastIndexOf(".") + 1);
                String newFileName =i +"."+ fileExtension;
                if (!Files.exists(uploadPath)) {
                    try {
                        Files.createDirectories(uploadPath);
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                }
                Path filePath = Paths.get(uploadPath.toString(), newFileName);
                list.add(filePath.toString());
                Files.write(filePath, files[i].getBytes());
            }

        return R.success("成功！！");
    }

}
